// "cell": "plugin://contactPlugin/cell"

//index.js
//获取应用实例
// id 		项目id
// name 	项目名称
// desc 	项目描述
// tag		项目标签
// address	项目地址
// avg_price	参考均价
// full_price 	参考总价
// floor_area	建筑面积
// property_type	物业类型
// build_type	建筑类型
// decoration	装修标准
// have_time	产权年限
// developer	开发商
// area 		所在区域
// company		物业公司
// build_area	楼盘地址
// sell_status 售卖状态(0未售，1在售)
// sell_area	售楼地址
// last_open 	最新开盘时间
// last_deal 	最近交房时间
// lat 		楼盘纬度
// lng			楼盘经度
// sell_lat	售楼地址纬度
// sell_lat	售楼地址经度
const app = getApp();
let globalData = app.globalData;
var sendPost = app.globalData.sendPost;
const amap = require('../../utils/amap-wx.js');
const key = app.globalData.key;
var myAmap = new amap.AMapWX({
    key: key
});
Page({
    data: {
        pid:'',
        currentId: '1',
        section: globalData.section,
        qian_img: globalData.qian_img,
        huxing_list: [],
        activeIndex: 0,
        tel: '',
        price: false, // 价格变动model
        start: false, // 开盘提醒model
        sell_info_btn: true, // 是否置业顾问详情
        scale: 13,
        is_focus: 0, //1关注楼盘 0未关注
        is_change: 0, //1是已订阅，0未订阅
        is_open: 0, //1是已订阅，0未订阅
        fang: {},
        img_list: [], // 轮播图列表
        seller: [], //销售顾问
        articleList: [], //楼盘动态
        aroundList: globalData.aroundList,
        status: null,
        isShow: false,
        markersData: [],
        markers: [],
        points: [],
        scale: 13,
        location: '',
        name: '',
        address: '',
        project_name:''//项目名称
    },
    //事件处理函数
    bindViewTap: function() {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    //点击户型进入详情
    huxinginfoTap: function(e) {
        var id = e.currentTarget.dataset.id;
        wx.redirectTo({
            url: '../huxing_info/index?id=' + id,
        })
    },

    //点击查看更多（顾问）
    sellerMore: function() {
        wx.redirectTo({
            url: '../seller/index'
        })
    },
    //点击查看更多(新闻)
    newsrMore: function() {
        wx.redirectTo({
            url: '../news/index'
        })
    },
    //点击进入置业顾问详情
    sellerInfo: function(e) {
        var $data = e.currentTarget.dataset;
        if (this.data.sell_info_btn) {
            wx.redirectTo({
                url: '../seller_info/index?id=' + $data.id,
            })
        }
    },
    //点击查看更多(新闻)
    sellerMore: function() {
        wx.redirectTo({
            url: '../seller/index'
        })
    },
    //在线订购
    todinggou: function() {
        wx.redirectTo({
            url: '../payPlan/index'
        })
    },
    //有奖推荐
    totuijian: function() {
        let data = {
          openid: globalData.openid
        }
        globalData.sendPost('custom/check-login', data).then(res => {
          console.log(res)
          if (res.status == 1) {
            var user_id = res.data.user_id;
            var invite_code = res.data.invite_code;
            var invite_qrcode = res.data.invite_qrcode;
            var identity = res.data.identity;
            wx.reLaunch({
              url: '../tuijian/index?user_id=' + user_id + '&invite_code=' + invite_code + '&invite_qrcode=' + invite_qrcode + '&identity=' + identity,
            })
          }else{
            wx.reLaunch({
              url: '../tuijian_reg/index?project_name=' + this.data.project_name + '&pid=' + this.data.pid,
            })
          }
        })
    },
    //电话咨询
    telClick: function(e) {
        // wx.getSetting({
        //     success: (res) => {
        //         if (res.authSetting.scope.phoneNumber){
        //             console.log(666);
        //         }
        //     }
        // }
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.tel
        })
    },
    onLoad: function (options) {
        this.setData({
          pid: options.pid
        })
        console.log(options.pid)
        this.getArticleList();
        if (app.globalData.employId && app.globalData.employId != '') {
            this.getData();
        } else {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.employIdCallback = employId => {
                if (employId != '') {
                    this.getData();
                }
            }
        }
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
        
    },
    // 初始化地图
    onReady() {
        this.mapCtx = wx.createMapContext('myMap');
    },
    getUserInfo: function(e) {
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    handleTap: getApp().globalData.handleTap,
    // 获取 用户手机号授权
    getPhoneNumber(e) {
        let tel = this.data.tel;
        if (e.detail.errMsg == "getPhoneNumber:ok") {
            new Promise((rev, rej) => {
                let data = {
                    openid: globalData.openid,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                    pid: globalData.pid
                }
                if (e.currentTarget.dataset.key == 'price' || e.currentTarget.dataset.key == 'start' || e.currentTarget.dataset.key == 'focus'){
                    data.type="1";
                }
                if (globalData.tel) {
                    tel = globalData.tel;
                    rev(tel)
                } else {
                    globalData.sendPost('wxuser/update-wxuser', data).then(res => {
                        globalData.tel = res.wxuser.phone;
                        tel = res.wxuser.phone;
                        rev(tel);
                    })
                }
            }).then(res1 => {
                globalData.tel = res1;
                this.setData({
                    tel: res1,
                })
                if (e.currentTarget.dataset.key == 'price') {
                    this.setData({
                        price: true
                    })
                } else if (e.currentTarget.dataset.key == 'start') {
                    this.setData({
                        start: true
                    })
                } else if (e.currentTarget.dataset.key == 'focus'){
                    let data = {
                        pid: globalData.pid,
                        openid: globalData.openid,
                        mobile: res1
                    }
                    globalData.sendPost('project/focus', data).then(res2 => {
                        if (res2.status == 1) {
                            this.setData({
                                is_focus: 1
                            })
                            globalData.showHint('关注成功');
                        }
                    })
                } else if (e.currentTarget.dataset.key == 'call'){
                    wx.makePhoneCall({
                        phoneNumber: res1,
                    })
                }
            })
        } else {
            console.log('没有获取权限');
        }
        return false;
    },
    //变价通知订阅
    //开盘提醒订阅
    dingyueTap(e) {
        var type = e.currentTarget.dataset.type;
        this.getDingyue(type);
    },
    // 关闭  变价 开盘 弹窗
    closeModel() {
        this.setData({
            price: false,
            start: false
        })
    },
    // 跳转贷款计算
    toLilv() {
        wx.redirectTo({
            url: '../interestRate/index',
        })
    },
    // 跳转预定页面
    todingou() {
        wx.redirectTo({
            url: '../payPlan/index',
        })
    },
    //去配套页面
    topeitao() {
        wx.redirectTo({
            url: '../peitao/index',
        })
    },
    tohuxing(e) {
        wx.redirectTo({
            url: '../huxing/index',
        })
    },
    infoMore(e) {
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '../xiangmu_more/index?id=' + id,
        })
    },
    // 进入页面获取数据
    getData() {
        let data = {
            pid: globalData.pid,
            openid: globalData.openid
        }
        globalData.sendPost('project/project-info', data).then(res => {
            if (res.status == 1) {
                this.setData({
                    img_list: res.banner,
                    fang: res.data,
                    seller: res.adviser,
                    huxing_list: res.house,
                    location: res.data.lat + ',' + res.data.lng,
                    is_focus: res.is_focus,
                    is_change: res.is_change,
                    is_open: res.is_open,
                    tel: res.phone,
                    project_name:res.data.name
                })
                console.log(res);
                this.getlocal();
            }
        })
    },
    // 点击复制微信号
    copyVx(event) {
        let vx = event.currentTarget.dataset.vx;
        var _this = this;
        wx.setClipboardData({
            data: vx,
            success(res) {
                globalData.showHint('微信号已复制成功');
            }
        })
    },
    // 轮播图跳转
    toImgUrl(e) {
        let imgUrl = e.currentTarget.dataset.url;
        wx.redirectTo({
            url: imgUrl,
        })
    },
    // 楼盘动态
    getArticleList() {
        let data = {
            pid: globalData.pid,
            pagesize: 3
        }
        globalData.sendPost('article/list', data).then(res => {
            if (res.status == 1) {
                // wx.showToast({
                //     title: '成功',
                // })
                this.setData({
                    articleList: res.data
                })
            }
        })
    },
    // 前往动态详情
    toArticle(event) {
        let id = event.currentTarget.dataset.id;
        let link_url = event.currentTarget.dataset.url;
        let title = event.currentTarget.dataset.title;
        if (link_url) {
            wx.navigateTo({
                url: '../news_info_webview/index?url=' + link_url,
            })
        } else {
            wx.navigateTo({
                url: '../news_info/index?news_id=' + id + '&title=' + title,
            })
        }

    },
    startmessage() {
        this.setData({
            sell_info_btn: false
        })
        console.log('请求企业微信')
    },
    // 动态更多
    newsrMore() {
        wx.navigateTo({
            url: '../news/index',
        })
    },
    tositeTap() {
        let _this = this;
        let lat=this.data.location.split(',')[0];
        let lng=this.data.location.split(',')[1];
        wx.authorize({
            scope: 'scope.userLocation',
            success: (res) => {
                wx.getLocation({ //获取当前经纬度
                    type: 'wgs84', //返回可以用于wx.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息  
                    success: function (res) {
                        wx.openLocation({ //​使用微信内置地图查看位置。
                            latitude: lat*1, //要去的纬度-地址
                            longitude: lng*1, //要去的经度-地址
                            name: _this.data.fang.name,
                        })
                    },
                    fail: (error) => {
                        console.log(error)
                    }
                })
            },
            fail: (res) => {
                wx.openSetting({
                    success: function (data) {
                        if (data.authSetting["scope.userLocation"] == true) {
                            wx.showToast({
                                title: '授权成功',
                                icon: 'success',
                                duration: 5000
                            })
                            _this.tositeTap();
                        } else {
                            wx.showToast({
                                title: '授权失败',
                                icon: 'none',
                                duration: 5000
                            })
                        }
                    }
                })
            },
        })
    },
    //预约接待
    toyuyue() {
        var tel = this.data.tel;
        wx.navigateTo({
            url: '../yuyue/index',
        })
    },
    getlocal() {
        var _this = this;
        myAmap.getRegeo({
            success: function(data) {
                var p_name = _this.data.fang.name;
                var p_lat = _this.data.fang.lat;
                var p_lng = _this.data.fang.lng;
                _this.setData({
                  markers: [{
                    iconPath: "../../images/icon/icon-dingwei.png",
                    latitude: p_lat,
                    longitude: p_lng,
                    width: 32,
                    height: 32,
                    label: {
                        content: p_name,
                        color: '#000',
                        fontSize: 12,
                        borderRadius: 5,
                        bgColor: '#fff',
                        padding: 6,
                        textAlign: 'center'
                    }
                  }],
                  markersData: [{
                    iconPath: "../../images/icon/icon-dingwei.png",
                    latitude: p_lat,
                    longitude: p_lng,
                    width: 32,
                    height: 32,
                    label: {
                      content: p_name,
                      color: '#000',
                      fontSize: 12,
                      borderRadius: 5,
                      bgColor: '#fff',
                      padding: 6,
                      textAlign: 'center'
                    }
                  }],
                });
            },
            fail: function(info) {
              var p_name = _this.data.fang.name;
              var p_lat = _this.data.fang.lat;
              var p_lng = _this.data.fang.lng;
              _this.setData({
                markers: [{
                  iconPath: "../../images/icon/icon-dingwei.png",
                  latitude: p_lat,
                  longitude: p_lng,
                  width: 32,
                  height: 32,
                  label: {
                    content: p_name,
                    color: '#000',
                    fontSize: 12,
                    borderRadius: 5,
                    bgColor: '#fff',
                    padding: 6,
                    textAlign: 'center'
                  }
                }],
                markersData: [{
                  iconPath: "../../images/icon/icon-dingwei.png",
                  latitude: p_lat,
                  longitude: p_lng,
                  width: 32,
                  height: 32,
                  label: {
                    content: p_name,
                    color: '#000',
                    fontSize: 12,
                    borderRadius: 5,
                    bgColor: '#fff',
                    padding: 6,
                    textAlign: 'center'
                  }
                }],
              });
            }
        })
    },
    getType(e) { //获取选择的附近关键词，同时更新状态
    console.log(this.data.markers)
        this.setData({
            status: e.currentTarget.dataset.type
        })
        this.getAround(e.currentTarget.dataset.keywords,'', e.currentTarget.dataset.id);
    },
    getAround(keywords, types, ids) { //通过关键词获取附近的点，只取前十个，同时保证十个点在地图中显示
        var _this = this;
        var myAmap = new amap.AMapWX({
            key: key
        });
        myAmap.getPoiAround({
            iconPath: _this.data.aroundList[ids].iconPath,
            querykeywords: keywords,
            querytypes: types,
            location: _this.data.location,
            radius:5000,
            success(data) {
                if (data.markers) {
                    var markers = [],
                        points = [],
                        markersData = _this.data.markersData;
                    for (var value of data.markers) {
                        if (value.id > 4) break;
                        if (value.id == 0) {
                            _this.setData({
                                name: value.name,
                                address: value.address,
                                isShow: true
                            })
                        }
                        markers.push({
                          id: value.id,
                          latitude: value.latitude,
                          longitude: value.longitude,
                          title: value.name,
                          iconPath: _this.data.aroundList[ids].iconPath,
                          width: 20,
                          height: 23,
                          anchor: {
                              x: .5,
                              y: 1
                          },
                          label: {
                              content: value.name,
                              color: '#000',
                              fontSize: 12,
                              borderRadius: 5,
                              bgColor: '#fff',
                              padding: 3,
                              x: 0,
                              y: -50,
                              textAlign: 'center'
                          }
                        });
                        points.push({
                            latitude: value.latitude,
                            longitude: value.longitude
                        })
                    }
                    var markersAll = markers.concat(markersData);
                    _this.setData({
                        markers: markersAll,
                        points: points
                    })
                }
            },
            fail: function(info) {
                wx.showToast({
                    title: 'info.code'
                })
            },
        })
    },
    getDingyue(type) {
        // type   1 是订阅变价  2 订阅开盘 
        let data = {
            pid: globalData.pid,
            openid: globalData.openid,
            type: type,
            mobile: this.data.tel,
        }
        globalData.sendPost('project/remind', data).then(res => {
            if (res.status == 1) {
                this.closeModel();
                if (type == 1) {
                    this.setData({
                        is_change: 1
                    })
                } else if (type == 2) {
                    this.setData({
                        is_open: 1
                    })
                }
                wx.showToast({
                    title: '订阅成功',
                    icon: 'success',
                    duration: 2000
                })
            }
        })

    },
    cancleFocus(e) {
        if (this.data.is_focus) {
            globalData.showHint('您已关注');
        }
    },
    showModel(event) {
        let key = event.currentTarget.dataset.key;
        if (key == 'price') {
            if (this.data.is_change) {
                globalData.showHint('您已订阅');
            } else {
                this.setData({
                    price: true
                })
            }
        } else if (key == 'start') {
            if (this.data.is_open) {
                globalData.showHint('您已订阅');
            } else {
                this.setData({
                    start: true
                })
            }
        }
    },
    stopPropagation(){}
})